package com.wtp.wallpaper.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtp.wallpaper.common.context.BaseContext;
import com.wtp.wallpaper.mapper.ScoreMapper;
import com.wtp.wallpaper.pojo.dto.ScoreDTO;
import com.wtp.wallpaper.pojo.entity.Score;
import com.wtp.wallpaper.rabbitmq.producer.RatingProducer;
import com.wtp.wallpaper.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private RatingProducer ratingProducer;

    @Override
    public int getListCountByUserId(Long id) {
        return Math.toIntExact(getScoreListByUserId(id).size());
    }



    @Override
    public List<Long> getPictureIdsByUserId(Long currentId) {
        // 使用 lambdaQuery 查询所有与 userId 匹配的 Collect 数据

        return lambdaQuery()
                .eq(Score::getUserId, currentId)
                .orderByDesc(Score::getId) //根据时间降序
                .list()  // 获取查询结果的集合
                .stream()  // 转换为 Stream
                .map(Score::getPicId)  // 提取 pictureId
                .toList();  // 收集为 List<Long>  // 返回 Long 数组
    }

    @Override
    public void setupScoreInUser(ScoreDTO scoreDTO) {
        Score score = BeanUtil.copyProperties(scoreDTO, Score.class);
        score.setUserId(Long.valueOf(BaseContext.getCurrentId()));
        save(score);

        ratingProducer.sendRatingMessage(JSON.toJSONString(scoreDTO));

//        Map<Long,ScoreSum> scoreSumMap = new HashMap<>();
//        Object o = redisTemplate.opsForValue().get(RedisConstant.SCORE_MAP);
//        if(o != null){
//            scoreSumMap = (Map) o;
//        }
//        Long picId = score.getPicId();
//        if(scoreSumMap.containsKey(picId)){
//            ScoreSum scoreSum = scoreSumMap.get(picId);
//            scoreSum.setScoreSum();
//        }else{
//
//        }
    }

    @Override
    public List<Score> getScoreListByUserId(Long id) {
        return lambdaQuery().eq(Score::getUserId,id).list();
    }
}
